<template>
  <div>
    <a-drawer
      :open="visible"
      @update:open="$emit('update:visible', $event)"
      title="人员分配"
      :width="900"
      placement="right"
      :closable="true"
      :mask-closable="false"
      class="employee-assignment-drawer"
    >
    <template #title>
      <div class="drawer-title">
        <team-outlined style="margin-right: 8px;" />
        人员分配
        <a-tag color="blue" style="margin-left: 8px;">{{ dispatchMethodText }}</a-tag>
      </div>
    </template>

    <div class="assignment-content">
      <!-- 当前选择概览 -->
      <div class="assignment-summary" v-if="dispatchMethod === 'assignee'">
        <a-card size="small" title="当前选择" style="margin-bottom: 16px;">
          <div class="summary-grid">
            <div class="summary-item">
              <div class="summary-label">负责人</div>
              <div class="summary-value">
                <a-tag v-if="selectedAssigneeInfo" color="blue" closable @close="removeAssignee">
                  <user-outlined />
                  {{ selectedAssigneeInfo.realName }}
                </a-tag>
                <span v-else style="color: #8c8c8c;">未选择</span>
              </div>
            </div>
            <div class="summary-item">
              <div class="summary-label">协同人员</div>
              <div class="summary-value">
                <!-- 调试信息：显示当前状态 -->
                <!-- selectedCollaborators: {{ selectedCollaborators }}, selectedCollaboratorInfos: {{ selectedCollaboratorInfos }} -->
                
                <a-space v-if="selectedCollaboratorInfos.length > 0" wrap>
                  <a-tag 
                    v-for="user in selectedCollaboratorInfos" 
                    :key="user.id" 
                    color="green"
                    closable
                    @close="removeCollaborator(user.id)"
                  >
                    <team-outlined />
                    {{ user.realName }}
                  </a-tag>
                </a-space>
                <span v-else style="color: #8c8c8c;">
                  无
                  <small style="color: #ccc; margin-left: 8px;" v-if="selectedCollaborators.length > 0">
                    (IDs: {{ selectedCollaborators.join(', ') }})
                  </small>
                </span>
              </div>
            </div>
          </div>
        </a-card>
      </div>

      <!-- 人员定位选择器 -->
      <EmployeeLocationPicker
        :customer-location="customerLocation"
        :customer-address="customerAddress"
        :selected-assignee="selectedAssignee"
        :selected-collaborators="selectedCollaborators"
        :current-assigned-users="currentAssignedUsers"
        :rejected-users="rejectedUsers"
        :current-executors="currentExecutors"
        :work-order-id="workOrderId"
        :start-time="startTime"
        :end-time="endTime"
        :selection-mode="dispatchMethod"
        @update:selected-assignee="handleAssigneeUpdate"
        @update:selected-collaborators="handleCollaboratorsUpdate"
        @select-assignee="handleSelectAssignee"
        @select-collaborator="handleSelectCollaborator"
        @view-schedule="handleViewSchedule"
        @employees-loaded="handleEmployeesLoaded"
        @location-geocoded="handleLocationGeocoded"
      />

      <!-- 已拒绝人员提示 -->
      <div v-if="rejectedUsers.length > 0" class="rejected-section">
        <a-alert
          type="warning"
          :message="`${rejectedUsers.length}人已拒绝`"
          show-icon
          style="margin-top: 16px;"
        >
          <template #description>
            <div class="rejected-list">
              <div v-for="rejected in rejectedUsers" :key="rejected.userId" class="rejected-item">
                <span class="rejected-name">{{ rejected.userName }}</span>
                <span class="rejected-role">{{ rejected.isResponsible ? '(负责人)' : '(协同人)' }}</span>
                <span class="rejected-reason">{{ rejected.rejectReason || '未填写理由' }}</span>
                <span class="rejected-time">{{ formatDateTime(rejected.rejectTime) }}</span>
              </div>
            </div>
          </template>
        </a-alert>
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <a-space>
          <a-button @click="handleCancel">
            取消
          </a-button>
          <a-button 
            type="primary" 
            @click="handleConfirm"
            :disabled="!canConfirm"
          >
            确认选择
          </a-button>
        </a-space>
      </div>
    </template>
  </a-drawer>

  <!-- 人员日程抽屉 -->
  <a-drawer
    :open="scheduleDrawerVisible"
    @update:open="val => scheduleDrawerVisible = val"
    title="人员工作日程"
    :width="800"
    placement="right"
    :closable="true"
    :mask-closable="true"
    :z-index="1100"
  >
    <template #title>
      <div class="drawer-title">
        <a-avatar :src="selectedEmployee?.avatar" size="small">
          {{ selectedEmployee?.realName?.charAt(0) }}
        </a-avatar>
        <span style="margin-left: 8px;">{{ selectedEmployee?.realName }} 的工作日程</span>
        <a-tag :color="getStatusColor(selectedEmployee?.status)" size="small" style="margin-left: 8px;">
          {{ getStatusText(selectedEmployee?.status) }}
        </a-tag>
      </div>
    </template>

    <div class="schedule-drawer-content">
      <!-- 使用工作日程组件 -->
      <WorkScheduleCalendar
        :employee-id="selectedEmployee?.id"
        :employee-name="selectedEmployee?.realName"
        @event-click="handleScheduleEventClick"
        @date-click="handleScheduleDateClick"
        @schedules-loaded="handleSchedulesLoaded"
        @year-change="handleScheduleYearChange"
        @month-change="handleScheduleMonthChange"
      />
    </div>
  </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { message } from 'ant-design-vue';
import {
  TeamOutlined,
  UserOutlined,
} from '@ant-design/icons-vue';
// @ts-ignore
import EmployeeLocationPicker from './EmployeeLocationPicker.vue';
// @ts-ignore
import WorkScheduleCalendar from '@/components/WorkScheduleCalendar.vue';

// 组件Props定义
interface Props {
  visible: boolean;
  customerLocation: {
    lng: number;
    lat: number;
  };
  customerAddress: string;
  selectedAssignee?: string;
  selectedCollaborators?: string[];
  currentAssignedUsers?: string[];
  rejectedUsers?: any[];
  currentExecutors?: any[];
  workOrderId?: string;
  startTime?: string;
  endTime?: string;
  dispatchMethod?: 'assignee' | 'pool' | 'provider' | 'auto';
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  selectedAssignee: '',
  selectedCollaborators: () => [],
  currentAssignedUsers: () => [],
  rejectedUsers: () => [],
  currentExecutors: () => [],
  workOrderId: '',
  startTime: '',
  endTime: '',
  dispatchMethod: 'assignee'
});

// 组件Emits定义
interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'update:selectedAssignee', value: string): void;
  (e: 'update:selectedCollaborators', value: string[]): void;
  (e: 'confirm', data: {
    assignee: string;
    assigneeInfo: any;
    collaborators: string[];
    collaboratorInfos: any[];
  }): void;
  (e: 'cancel'): void;
  (e: 'location-geocoded', location: { lng: number; lat: number }): void;
}

const emit = defineEmits<Emits>();

// 响应式数据
const selectedAssignee = ref(props.selectedAssignee);
const selectedCollaborators = ref([...props.selectedCollaborators]);
const selectedAssigneeInfo = ref<any>(null);
const selectedCollaboratorInfos = ref<any[]>([]);
const allEmployees = ref<any[]>([]);

// 人员日程相关
const scheduleDrawerVisible = ref(false);
const selectedEmployee = ref<any>(null);

// 计算属性
const dispatchMethodText = computed(() => {
  const texts = {
    assignee: '派单给负责人',
    pool: '派单到工单池',
    provider: '派单到服务商',
    auto: '自动分配'
  };
  return texts[props.dispatchMethod] || '未知';
});

const canConfirm = computed(() => {
  if (props.dispatchMethod === 'assignee') {
    return !!selectedAssignee.value;
  }
  return true;
});

// 事件处理函数
const handleAssigneeUpdate = (value: string) => {
  selectedAssignee.value = value;
  emit('update:selectedAssignee', value);
};

const handleCollaboratorsUpdate = (value: string[]) => {
  console.log('EmployeeAssignmentDrawer - handleCollaboratorsUpdate:', value);
  selectedCollaborators.value = value;
  emit('update:selectedCollaborators', value);
};

const handleSelectAssignee = (employee: any) => {
  selectedAssignee.value = employee.id;
  selectedAssigneeInfo.value = employee;
  emit('update:selectedAssignee', employee.id);
  
  // 如果之前是协同人员，从协同人员中移除
  if (selectedCollaborators.value.includes(employee.id)) {
    removeCollaborator(employee.id);
  }
};

const handleSelectCollaborator = (employee: any) => {
  console.log('EmployeeAssignmentDrawer - handleSelectCollaborator:', employee.realName, employee.id);
  console.log('当前 selectedCollaborators.value:', selectedCollaborators.value);
  console.log('当前 selectedCollaboratorInfos.value:', selectedCollaboratorInfos.value.map(info => info.id));
  
  // 双重检查：既要检查ID数组，也要检查信息数组
  const idExists = selectedCollaborators.value.includes(employee.id);
  const infoExists = selectedCollaboratorInfos.value.find(info => info.id === employee.id);
  
  if (!idExists) {
    selectedCollaborators.value.push(employee.id);
    console.log('添加后 selectedCollaborators.value:', selectedCollaborators.value);
    
    // 立即更新协同人员信息数组（双重检查避免重复）
    if (!infoExists) {
      selectedCollaboratorInfos.value.push(employee);
      console.log('立即更新 selectedCollaboratorInfos:', selectedCollaboratorInfos.value);
    } else {
      console.warn('协同人员信息已存在，跳过添加:', employee.id);
    }
    
    emit('update:selectedCollaborators', selectedCollaborators.value);
  } else {
    console.warn('协同人员ID已存在，跳过添加:', employee.id);
  }
  
  // 如果是负责人，清除负责人身份
  if (selectedAssignee.value === employee.id) {
    selectedAssignee.value = '';
    selectedAssigneeInfo.value = null;
    emit('update:selectedAssignee', '');
  }
};

const removeAssignee = () => {
  selectedAssignee.value = '';
  selectedAssigneeInfo.value = null;
  emit('update:selectedAssignee', '');
};

const removeCollaborator = (userId: string) => {
  console.log('EmployeeAssignmentDrawer - removeCollaborator:', userId);
  selectedCollaborators.value = selectedCollaborators.value.filter(id => id !== userId);
  
  // 立即更新协同人员信息数组
  selectedCollaboratorInfos.value = selectedCollaboratorInfos.value.filter(info => info.id !== userId);
  console.log('移除后 selectedCollaboratorInfos:', selectedCollaboratorInfos.value);
  
  emit('update:selectedCollaborators', selectedCollaborators.value);
};

const handleViewSchedule = (employee: any) => {
  selectedEmployee.value = employee;
  scheduleDrawerVisible.value = true;
};

const handleEmployeesLoaded = (employees: any[]) => {
  allEmployees.value = employees;
  
  // 根据选中的ID更新完整信息
  if (selectedAssignee.value && !selectedAssigneeInfo.value) {
    selectedAssigneeInfo.value = employees.find(emp => emp.id === selectedAssignee.value);
  }
  
  // 同步协同人员信息（去除条件限制，确保始终同步）
  if (selectedCollaborators.value.length > 0) {
    selectedCollaboratorInfos.value = employees.filter(emp => selectedCollaborators.value.includes(emp.id));
  } else {
    selectedCollaboratorInfos.value = [];
  }
};

const handleLocationGeocoded = (location: { lng: number; lat: number }) => {
  console.log('抽屉组件接收到地理编码结果:', location);
  // 向父组件传递地理编码事件
  emit('location-geocoded', location);
};

const handleConfirm = () => {
  if (!canConfirm.value) {
    message.warning('请完善人员选择');
    return;
  }

  // 去重处理，确保没有重复的协同人员
  const uniqueCollaborators = [...new Set(selectedCollaborators.value)];
  const uniqueCollaboratorInfos = selectedCollaboratorInfos.value.filter((info, index, self) => 
    self.findIndex(item => item.id === info.id) === index
  );

  console.log('确认前数据检查:', {
    原始协同人员IDs: selectedCollaborators.value,
    去重后协同人员IDs: uniqueCollaborators,
    原始协同人员信息: selectedCollaboratorInfos.value,
    去重后协同人员信息: uniqueCollaboratorInfos
  });

  emit('confirm', {
    assignee: selectedAssignee.value,
    assigneeInfo: selectedAssigneeInfo.value,
    collaborators: uniqueCollaborators,
    collaboratorInfos: uniqueCollaboratorInfos
  });
  
  emit('update:visible', false);
};

const handleCancel = () => {
  emit('cancel');
  emit('update:visible', false);
};

// 日程相关事件处理
const handleScheduleEventClick = (schedule: any) => {
  console.log('日程事件点击:', schedule);
};

const handleScheduleDateClick = (date: any) => {
  console.log('日程日期点击:', date.format('YYYY-MM-DD'));
};

const handleSchedulesLoaded = (schedules: any[]) => {
  console.log('日程加载完成:', schedules.length, '条记录');
};

const handleScheduleYearChange = (year: number) => {
  console.log('日程年份变化:', year);
};

const handleScheduleMonthChange = (month: number) => {
  console.log('日程月份变化:', month);
};

// 工具函数
const getStatusColor = (status: string) => {
  const colors = {
    available: 'green',
    busy: 'orange',
    offline: 'red'
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts = {
    available: '空闲',
    busy: '忙碌',
    offline: '离线'
  };
  return texts[status] || '未知';
};

const formatDateTime = (dateTimeString: string) => {
  if (!dateTimeString) return '';
  
  try {
    const date = new Date(dateTimeString);
    
    if (isNaN(date.getTime())) {
      return dateTimeString;
    }
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  } catch (error) {
    console.error('日期格式化失败:', error);
    return dateTimeString;
  }
};

// 监听props变化，同步到本地状态
import { watch } from 'vue';

watch(() => props.selectedAssignee, (newVal) => {
  selectedAssignee.value = newVal;
}, { immediate: true });

watch(() => props.selectedCollaborators, (newVal) => {
  console.log('EmployeeAssignmentDrawer - watch selectedCollaborators:', newVal);
  selectedCollaborators.value = [...newVal];
  
  // 同时更新协同人员信息（仅在有员工数据且本地信息不完整时更新）
  if (allEmployees.value.length > 0) {
    const expectedInfos = allEmployees.value.filter(emp => newVal.includes(emp.id));
    
    // 检查是否需要更新（避免与立即更新冲突）
    const currentIds = selectedCollaboratorInfos.value.map(info => info.id);
    const needsUpdate = newVal.length !== currentIds.length || 
                       !newVal.every(id => currentIds.includes(id));
    
    if (needsUpdate) {
      selectedCollaboratorInfos.value = expectedInfos;
      console.log('watch更新 selectedCollaboratorInfos:', selectedCollaboratorInfos.value);
    }
  }
}, { immediate: true, deep: true });
</script>

<style lang="less" scoped>
.employee-assignment-drawer {
  .drawer-title {
    display: flex;
    align-items: center;
  }

  .assignment-content {
    padding: 0;
    
    .assignment-summary {
      .summary-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
        
        .summary-item {
          .summary-label {
            font-size: 12px;
            color: #8c8c8c;
            margin-bottom: 4px;
            font-weight: 500;
          }
          
          .summary-value {
            min-height: 32px;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 4px;
          }
        }
      }
    }
  }

  .rejected-section {
    .rejected-list {
      .rejected-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 4px;
        font-size: 12px;

        &:last-child {
          margin-bottom: 0;
        }

        .rejected-name {
          font-weight: 500;
          color: #ff4d4f;
        }

        .rejected-role {
          color: #8c8c8c;
          font-size: 11px;
        }

        .rejected-reason {
          color: #8c8c8c;
          flex: 1;
          
          &:before {
            content: "理由: ";
            color: #595959;
          }
        }

        .rejected-time {
          color: #8c8c8c;
          font-size: 11px;
        }
      }
    }
  }

  .drawer-footer {
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #f0f0f0;
    padding-top: 16px;
  }
}

.schedule-drawer-content {
  padding: 16px 0;
}

// 全局抽屉层级样式
:global(.ant-drawer-wrapper-body) {
  overflow: hidden;
}
</style>
